# -*- coding: utf-8 -*-
from selenium import webdriver  # 获取天气状况（7天）
from lxml import etree


def write_log(date, weather, c1, c2, w_wind):
    with open('log.txt', 'a+', encoding='utf-8') as f:
        f.write(date + ' ' + weather + ' ' + c1 + ' ' + c2 + ' ' + w_wind)
        f.write("\n")


def one_week(text):
    news = text.xpath('//*[@id="7d"]/ul/li')  # 获取含有七天天气状况的列表
    for t in news:
        date = t.xpath('h1/text()')[0]  # 日期
        weather = t.xpath('p[1]/text()')[0]  # 天气
        c1 = t.xpath('p[2]/span/text()')  # 最高温度
        c2 = t.xpath('p[2]/i/text()')[0]  # 最低温度
        wind = t.xpath('p[3]/em/span/@title')  # 风向，风力
        if (c1 == []):
            c1 = " "
        else:
            c1 = c1[0]
        w_wind = ''
        for i in range(len(wind)):
            w_wind += wind[i] + ','
        print(date, weather, c1, c2, w_wind)
        write_log(date, weather, c1, c2, w_wind)
    #   ['26日（今天）'] ['多云'] [] ['18℃'] ['西风']
    #   ['27日（明天）'] ['多云转晴'] ['28℃'] ['18℃'] ['东风', '无持续风向']


if __name__ == '__main__':
    driver = webdriver.Firefox()
    driver.get("http://www.weather.com.cn/weather/101210101.shtml")
    html = driver.page_source
    driver.quit()
    text = etree.HTML(html)
    one_week(text)
